package com.cg.controller;

import com.cg.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ServiceController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;



    /**
     * 获取所有服务
     * @return
     */
    @RequestMapping("/services")
    public Object services(){
        return discoveryClient.getInstances("demo-producer");
    }

    /**
     * 从所有服务中选择一个服务(轮询)
     * @return
     */
    @RequestMapping("/discover")
    public Object discover(){
        return loadBalancerClient.choose("demo-producer").getUri().toString();
    }

    @RequestMapping("/restTemplate")
    public List<User> restTemplate(){
        System.out.println(loadBalancerClient.choose("demo-producer").getUri().toString());
        System.out.println(loadBalancerClient.choose("demo-producer").getPort());
//        return restTemplate.getForObject("http://demo-producer/get7070",String.class);
        List<User> users = restTemplate.getForObject("http://demo-producer/findAllUser",List.class);
        return users;

    }

}
